import requests
import json
import os
import shutil


def download_music(items, dir_name):
    print("开始下载歌单: %s" % dir_name)
    if os.path.exists(dir_name):
        shutil.rmtree(dir_name)

    if not os.path.exists(dir_name):
        os.mkdir(dir_name)
    for music in items:
        music_title = music['title']
        music_download_url = music['url']
        music_file_houzhui = music_download_url[music_download_url.rfind('.') + 1:]
        file_name = music_title + "." + music_file_houzhui
        print(music_title)
        print(music_download_url)

        r = requests.get(music_download_url, stream=True)
        # download started
        with open(dir_name + "/" + file_name, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024 * 1024):
                if chunk:
                    f.write(chunk)

        print("%s 下载完成!\n" % file_name)
    print("歌单: %s 全部下载完" % dir_name)

def run():
    json_content = load_json()
    for playerlist_id in json_content['playerlists']:
        print(playerlist_id)
        playerlist = json_content[playerlist_id]
        print(playerlist)
        # 歌单名称
        playerlist_name = playerlist['info']['title']
        print(playerlist_name)
        # 具体歌曲列表
        tracks = playerlist['tracks']
        download_music(tracks, playerlist_name)


def load_json():
    # json文件转python
    with open('listen1_backup.json', encoding='utf8') as fp:
        python = json.load(fp)
        print(python)
        return python


if __name__ == '__main__':
    run()
